package com.lkd.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.dao.ChannelDao;
import com.lkd.http.controller.vo.ChannelConfigReq;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.SkuEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.ChannelService;
import com.lkd.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelDao, ChannelEntity> implements ChannelService {


    @Autowired
    private SkuService skuService;

    @Override
    public List<ChannelEntity> channelListByInnerCode(String innerCode) {
        return baseMapper.getChannelsByInnerCode(innerCode);
    }

    @Override
    public boolean channelConfig(ChannelConfigReq channelConfigReq) {
        // 给货道表中的sku_id 赋值  update tb_channel set sku_id = #{skuId},current_capacity=0,price=? where channel_code = #{channelCode} and inner_code = #{innerCode}
        List<ChannelEntity> channelList = channelConfigReq.getChannelList();
        if(CollUtil.isEmpty(channelList)){
            throw new LogicException("货道配置不能为空");
        }

        for (ChannelEntity channelEntity : channelList) {
            Long skuId = channelEntity.getSkuId();
            if(skuId!=0){
                SkuEntity skuEntity = skuService.getById(skuId);
                channelEntity.setPrice(skuEntity.getPrice());
            }else{
                channelEntity.setPrice(0);

            }
            channelEntity.setCurrentCapacity(0);
            channelEntity.setSkuId(channelEntity.getSkuId());
            channelEntity.setUpdateTime(LocalDateTime.now());

            // 构建条件  where channel_code = #{channelCode} and inner_code = #{innerCode}
            LambdaUpdateWrapper<ChannelEntity> qw = new LambdaUpdateWrapper<>();
            qw.eq(ChannelEntity::getChannelCode,channelEntity.getChannelCode());
            qw.eq(ChannelEntity::getInnerCode,channelConfigReq.getInnerCode());

            // channelEntity使用了赋值的 set sku_id = #{skuId},current_capacity=0,price=?
            update(channelEntity,qw);

        }


        return true;
    }
}
